<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="80px">
      <!-- <el-form-item label="所属租户组" prop="tenantGroupId">
        <el-select v-model="queryParams.tenantGroupId" filterable clearable placeholder="选择所属租户组" style="width: 200px">
          <el-option v-for="item in groupList" :key="item.tenantGroupName" :label="item.tenantGroupName"
            :value="item.tenantGroupId" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="参数键名" prop="configKey">
        <el-input v-model.trim="queryParams.configKey" placeholder="请输入" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['gc:zhzpz:xz']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="tenantList">
      <el-table-column label="序号" type="index" width="100" />
      <!-- <el-table-column label="租户组" prop="tenantGroupName" /> -->
      <el-table-column label="参数键名" prop="configKey" />
      <el-table-column label="参数键值" prop="configValue" />
      <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="300" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button v-hasPermi="['gc:zhzpz:xg']" link type="primary" icon="Edit"
              @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button v-hasPermi="['gc:zhzpz:sc']" link type="primary" icon="Delete"
              @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改租户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <!-- <el-form-item label="所属租户组" prop="tenantGroupId">
          <el-select v-model="form.tenantGroupId" placeholder="选择所属租户组" style="width: 240px">
            <el-option v-for="item in groupList" :key="item.tenantGroupName" :label="item.tenantGroupName"
              :value="item.tenantGroupId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model.trim="form.configKey" :disabled="title == '修改租户组配置'" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model.trim="form.configValue" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="tenantIndex">
import {
  listTenantConfig,
  addTenantConfig,
  delTenantConfig,
  editTenantConfig
} from "@/api/system/tenantconfig";
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listgroup
} from "@/api/system/tenantgroup";
import {
  listapplicant,
} from "@/api/system/applicant";
import useUserStore from '@/store/modules/user';

const tenantGroupId = useUserStore().tenant.tenantGroupId;

import ImageUpload from "@/components/ImageUpload"
const router = useRouter();
const { proxy } = getCurrentInstance();
const tenantList = ref([]);
const groupList = ref([]);
const appLicationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const roleRef = ref()
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);



const data = reactive({
  form: {
    configKey: "",
    configValue: "",
    remark: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reasonable: false,
  },
  rules: {
    configKey: [{ required: true, message: "请输入", trigger: "blur" }],
    configValue: [{ required: true, message: "请输入", trigger: "blur" }],
   
  },
});


const { queryParams, form, rules } = toRefs(data);


/** 查询租户列表 */
function getList() {
  loading.value = true;
  const data = Object.assign({}, queryParams.value);
  data.tenantGroupId = tenantGroupId;
  listTenantConfig(data).then(response => {
    tenantList.value = response.rows
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询租户组列表 */
function getGroup() {
  listgroup({ pageNum: 1, pageSize: 10000 }).then(response => {
    groupList.value = response.rows;
    resetGroup()
    getList();
  });
}

// 初始化租户组
const resetGroup = ()=>{
  let arr = groupList.value.filter(item => {
    return item.tenantGroupId == tenantGroupId
  });
  if (arr.length > 0) {
    queryParams.value.tenantGroupId = arr[0].tenantGroupId
  }
}

/** 查询应用列表 */
function getAppLication() {
  listapplicant({ pageNum: 1, pageSize: 10000 }).then(response => {
    appLicationList.value = response.rows
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  resetGroup();
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  let data = {
    ids: [row.id]
  }
  proxy.$modal.confirm('是否确认删除当前租户组?').then(function () {
    return delTenantConfig(data);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    configKey: "",
    configValue: "",
    remark: "",
  };
}

/** 添加租户 */
function handleAdd() {
  reset();
  open.value = true;
  rules.value['adminPassword'] = [{ required: true, message: "超过密码不能为空", trigger: "blur" }];
  title.value = "添加租户组配置";
  setTimeout(() => {
    roleRef.value.resetFields()
  }, 100)
}

/** 修改租户 */
async function handleUpdate(row) {
  reset();
  form.value = Object.assign({},row)
  open.value = true;
  title.value = "修改租户组配置";
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (title.value == "修改租户组配置") {
        let data = Object.assign({},form.value);
        data.tenantGroupId = tenantGroupId;
        editTenantConfig(data).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        let data = Object.assign({},form.value);
        data.tenantGroupId = tenantGroupId;
        addTenantConfig(data).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 选择租户权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([]);
  }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.tenantId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openDataScope.value = false;
      getList();
    });
  }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}

getGroup();
getAppLication();

</script>